package com.toilet.easyvideo.security;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.toilet.easyvideo.config.JWTConfig;
import com.toilet.easyvideo.constant.JWTConstant;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.nio.file.AccessDeniedException;

/**
 * @description: JWT过滤器
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private SysUserAuthorizeService userService;
    @Resource
    private JWTConfig jwtConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //从请求头中获取token
        String jwtToken = request.getHeader(jwtConfig.getHeader());
        try {
            if (ObjectUtil.isNotEmpty(jwtToken)) {
                if (jwtConfig.verifyToken(jwtToken)) {
                    try {
                        //token可用
                        JWT jwt = JWTUtil.parseToken(jwtToken).setKey(jwtConfig.getAppSecret().getBytes());
                        JWTPayload payload = jwt.getPayload();
                        String uniqueKey = (String) payload.getClaim(JWTConstant.UNIQUE_KEY);
                        log.info("解析出来的的用户名：{}", uniqueKey);
                        UserDetails user = userService.loadUserByUsername(uniqueKey);
                        log.info("用户的账号和密码为：{},{}", user.getUsername(), user.getPassword());


                        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
//                        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(
//                                user.getUsername(), user.getPassword(), user.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                    } catch (Exception e) {
                        log.error("登录异常 ：", e);
                        throw new AccessDeniedException(e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            log.info("校验异常 ", e);
            throw new AccessDeniedException(e.getMessage());
        }
        filterChain.doFilter(request, response);//继续过滤
    }
}
